<!-- 任务管理 -->
<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import router from '@/router'
import type { IDbAction, IDbSearchConfig, IDbSelect, IDbTable, ITagData } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import { ENUM_MENU_NAME_TASK } from '@/config/menu'
import { ENUM_BTN_AUTH_TASK } from '@/config/btn'
import * as taskApi from '@/api/task'
import { TASK_STATUS_LIST, ENUM_TASK_STATUS } from './config/config'
import TaskInfo from './comps/TaskInfo.vue'
import TaskExecute from './comps/TaskExecute.vue'
import MarkDialog from './comps/MarkDialog.vue'

// 执行器列表
const executorList = ref<IDbSelect[]>([])
// 搜索栏配置
const searchConfig = computed<IDbSearchConfig[]>(() => {
  const configList: IDbSearchConfig[] = [
    { label: '状态', prop: 'triggerStatus', type: 'select', list: TASK_STATUS_LIST, options: { clearable: false } },
    { label: '执行器', prop: 'jobGroup', type: 'select', list: executorList.value },
    { label: '任务描述', prop: 'jobDesc', type: 'input' },
    { label: 'JobHandler', prop: 'executorHandler', type: 'input' },
    { label: '负责人', prop: 'author', type: 'input' }
  ]
  return configList
})

// 表格数据
const tableData = reactive<IDbTable>({
  columns: [
    { label: '任务ID', prop: 'id', width: '100px' },
    { label: '任务描述', prop: 'jobDesc', minWidth: '100px' },
    { label: '调度类型', prop: 'scheduleType', minWidth: '100px' },
    { label: '运行模式', prop: 'glueType', minWidth: '100px' },
    { label: '负责人', prop: 'author', width: '150px' },
    {
      label: '状态',
      prop: 'triggerStatus',
      width: '100px',
      type: 'tag',
      tagFunc: (scoped) => {
        const curStatus = TASK_STATUS_LIST.find((item) => item.value == scoped.row.triggerStatus)
        const params: ITagData = { label: curStatus?.label || '', type: curStatus?.tagType || '' }
        return params
      }
    },

    { label: '查询日志', prop: 'log', type: 'slot', width: '100px' },
    { label: '注册节点', prop: 'register', type: 'slot', width: '100px' },
    { label: '下次执行时间', prop: 'execute', type: 'slot', width: '120px' },
    { label: '操作', prop: 'handle', fixed: 'right', type: 'slot', width: '150px' }
  ],
  data: [],
  total: 0,
  search: {
    pageNum: 1,
    pageSize: 20,
    triggerStatus: ENUM_TASK_STATUS['全部'],
    jobGroup: '',
    jobDesc: '',
    executorHandler: '',
    author: ''
  }
})

// 弹窗数据
const taskInfoRef = ref<InstanceType<typeof TaskInfo>>()
const taskExeRef = ref<InstanceType<typeof TaskExecute>>()
const markDialogRef = ref<InstanceType<typeof MarkDialog>>()
const dialogData = reactive({
  title: '', // 详情-弹窗标题
  disabled: false // 详情-是否禁用
})

initData()

/**
 * 获取表格数据
 */
function getDataList() {
  taskApi.getTaskManagekByPage(tableData.search).then((res) => {
    if (res.success) {
      tableData.total = res.data?.total || 0
      tableData.data = res.data?.rows || []
    }
  })
}
/**
 * 点击添加
 */
function addClick() {
  dialogData.title = '添加任务'
  dialogData.disabled = false
  taskInfoRef.value?.init()
}
/**
 * 点击详情/编辑
 */
function infoClick(row: any, disabled: boolean) {
  dialogData.title = disabled ? '任务详情' : '编辑任务'
  dialogData.disabled = disabled
  taskInfoRef.value?.init(row)
}
/**
 * 点击删除
 */
function delClick(scoped: any) {
  useNotic().confirm(`您确定要删除第${scoped.$index + 1}个任务吗？`, (flag) => {
    if (flag) {
      taskApi.delTaskManage(scoped.row.id).then((res) => {
        if (res.success) {
          useNotic().success('删除成功')
          getDataList()
        }
      })
    }
  })
}
/**
 * 点击执行一次
 */
function onceClick(scoped: any) {
  taskExeRef.value?.init(scoped.row.id)
}
/**
 * 点击查询日志
 */
function logClick(row: any) {
  router.push({ name: ENUM_MENU_NAME_TASK['调度日志'], query: { jobGroup: row.jobGroup, jobId: row.id } })
}
/**
 * 点击注册节点
 */
function registerClick(row: any) {
  taskApi.getTaskManageDetail(row.jobGroup).then((res) => {
    if (res.success) {
      const content = res.data?.data?.addressList || ''
      markDialogRef.value?.init('注册节点', content.replace(',', '<br />'))
    }
  })
}
/**
 * 点击下次执行时间
 */
function nextClick(row: any) {
  taskApi.getTaskManageNextExecuteTime({ scheduleConf: row.scheduleConf, scheduleType: row.scheduleType }).then((res) => {
    if (res.success) {
      const contentList = res.data?.data || []
      markDialogRef.value?.init('下次执行时间', contentList.join('<br />'))
    }
  })
}
/**
 * 状态切换
 */
function statusClick(scoped: any) {
  let reqFunc = taskApi.startTaskManage
  let des = '启动'
  if (scoped.row.triggerStatus == ENUM_TASK_STATUS['启动']) {
    reqFunc = taskApi.stopTaskManage
    des = '停止'
  }
  reqFunc(scoped.row.id).then((res) => {
    if (res.success) {
      useNotic().success(`${des}成功`)
      getDataList()
    }
  })
}
/**
 * 设置表格按钮
 */
function setBtnList(scoped: any) {
  const list: IDbAction[] = [
    { label: '详情', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:查'], onClick: () => infoClick(scoped.row, true) },
    { label: '编辑', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:改'], onClick: () => infoClick(scoped.row, false) },
    { label: '删除', type: 'danger', auth: ENUM_BTN_AUTH_TASK['任务管理:删'], onClick: () => delClick(scoped) },
    { label: '执行一次', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:执行'], onClick: () => onceClick(scoped) },
    {
      label: scoped.row.triggerStatus == ENUM_TASK_STATUS['启动'] ? '停止' : '启动',
      type: 'primary',
      auth: ENUM_BTN_AUTH_TASK['任务管理:启停'],
      onClick: () => statusClick(scoped)
    }
    // { label: '查询日志', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:查'], onClick: () => logClick(scoped) },
    // { label: '注册节点', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:查'], onClick: () => registerClick(scoped) },
    // { label: '下次执行时间', type: 'primary', auth: ENUM_BTN_AUTH_TASK['任务管理:查'], onClick: () => nextClick(scoped) }
  ]
  return list
}
/**
 * 初始化
 */
function initData() {
  taskApi.getTaskExecutorkByPage({ pageNum: 1, pageSize: 99 }).then((res) => {
    if (res.success) {
      const rows = res.data?.rows || []
      executorList.value = rows.map((item: any) => {
        return { label: item.appname, value: item.id }
      })
      getDataList()
    }
  })
}
</script>

<template>
  <dui-page :search-config="searchConfig" :search-data="tableData.search" @search="getDataList">
    <template #btn>
      <db-auth-btn :auth="ENUM_BTN_AUTH_TASK['任务管理:增']" type="primary" iconType="add" @click="addClick">
        添加任务
      </db-auth-btn>
    </template>
    <template #default>
      <dui-table
        :data="tableData.data"
        :columns="tableData.columns"
        :total="tableData.total"
        :search="tableData.search"
        @search="getDataList"
      >
        <template #logSlot="scoped">
          <el-button type="primary" link @click="logClick(scoped.row)">查看</el-button>
        </template>
        <template #registerSlot="scoped">
          <el-button type="primary" link @click="registerClick(scoped.row)">查看</el-button>
        </template>
        <template #executeSlot="scoped">
          <el-button type="primary" link @click="nextClick(scoped.row)">查看</el-button>
        </template>
        <template #handleSlot="scoped">
          <dui-action :list="setBtnList(scoped)" />
        </template>
      </dui-table>
      <!-- 详情弹窗 -->
      <TaskInfo ref="taskInfoRef" :executorList="executorList" v-bind="dialogData" @refresh="getDataList" />
      <!-- 执行一次弹窗 -->
      <TaskExecute ref="taskExeRef" @refresh="getDataList" />
      <!-- 文本弹窗 -->
      <MarkDialog ref="markDialogRef" />
    </template>
  </dui-page>
</template>
